// * 
// * ExPOUND Page Drawing
// * 
// * 
// * @copyright 2007 Loughborough University
// * @license http://www.gnu.org/licenses/gpl.txt
// * @version 0.0.0.1
// * @since Jan 2010
// * /

import classes.Layer;
import classes.Page;
import classes.layers.BlankDrawingLayerWrapper;

import com.roguedevelopment.objecthandles.ObjectHandles;
import com.roguedevelopment.objecthandles.example.MoveableTextArea;
import com.roguedevelopment.objecthandles.example.TextDataModel;

import flash.events.MouseEvent;

import mx.containers.HBox;
import mx.controls.Alert;
import mx.controls.Image;
import mx.controls.Label;
import mx.core.Application;
import mx.events.DragEvent;


//include "../mxml_views/text_tools.mxml";

public function ClearPage():void{
	//remove all the children on the main canvas display area.
	Application.application.MainCanvas.removeAllChildren()
}

public function DrawSelectedPage(CurrentPage:int):Boolean{

	//clear all the object handles that may be still about.
	//objectHandles.selectionManager.clearSelection()
	Application.application.oh.selectionManager.clearSelection();
	
	drawCompulsoryComponents();
	
	//with the page number obtain an instance of the layers for the page
	var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[CurrentPage];
	var thisLayer:Layer = new Layer();

//check to see how many layers there are
//Alert.show(thisPage.layers.length.toString());	
	
	//loop through all of the page layers in turn and process.
	for(var eachlayer:int = 0 ; eachlayer<thisPage.layers.length; eachlayer++){
		thisLayer = thisPage.layers[eachlayer];	
	
		//get the layer type and then process as per type
		switch (thisLayer.data){
			case "Audio": 	
	    		Draw_Audio(thisLayer);
	        	break;
	        case "Image":							
	        
	        	Draw_Image(thisLayer);
	        	break;
	        case "Text":
	        	//currently pass the plain text as the html is not being rendered correctly
	        	Draw_Text(thisLayer);
	        	break;
	        case "Drawing":
	        	Draw_Drawing(thisLayer);
	        	break;
	        
			default:
	        	
	        	break;
	 }
	}
	
	return true;
}

private function StripStringSpaces(str:String):String{		
	var patten:RegExp = /\s+/g;
	var returnstr:String;
	
	returnstr = str.replace(patten, "");
		
	return returnstr;
}

//[Bindable] protected var dataModel:DataModel;
[Bindable] protected var dataModel:TextDataModel;


public function Draw_Text(objLayer:Layer):void{
		
	
	var screenDisplay:TextDataModel = new TextDataModel();
	screenDisplay.x = objLayer.obj_x_pos;
    screenDisplay.y = objLayer.obj_y_pos;
    screenDisplay.width = objLayer.obj_width;
    screenDisplay.height = objLayer.obj_height;
    screenDisplay.text = objLayer.obj_original_text;   
    screenDisplay.Name = objLayer.label;
    //screenDisplay.name= drawingName;    
    screenDisplay.rotation = objLayer.obj_rotation;
    
    var MovableText:MoveableTextArea = new MoveableTextArea();
	MovableText.model = screenDisplay;
	MovableText.id = objLayer.label;  
	MovableText.name = objLayer.label;   
	MovableText.editable = false;
	//MovableText.opaqueBackground  = true;
	MovableText.alpha = 0;
    				

	Application.application.oh.registerComponent(screenDisplay, MovableText);

	Application.application.MainCanvas.addChild(MovableText);
}

public function Draw_Audio(objLayer:Layer):void{
	          	
    var CreatedContainer:HBox = new HBox();
    CreatedContainer.id = objLayer.label;
    CreatedContainer.name = objLayer.label;
    CreatedContainer.x = objLayer.obj_x_pos;
    CreatedContainer.y = objLayer.obj_y_pos;
    CreatedContainer.rotation = objLayer.obj_rotation;
         	
    var btnPlay:Button = new Button();
    btnPlay.id = "btnPlay" + objLayer.label;
    btnPlay.label = "Play";
            	     	
    CreatedContainer.addChild(btnPlay);
            	
    var btnPause:Button = new Button();
    btnPause.id = "btnPause" + objLayer.label;
    btnPause.label ="Pause";
            	
    CreatedContainer.addChild(btnPause);
            	
    var btnStop:Button = new Button();
    btnStop.id = "btnStop" + objLayer;
    btnStop.label ="Stop";
    //btnStop.setStyle("icon", "@Embed(source='../images/icons/audio/control_stop_blue.png')");
            	            	
    CreatedContainer.addChild(btnStop);
   
    
  //  Application.application.oh.registerComponent(CreatedContainer, AudioSimpleDataModel);
  	Application.application.oh.registerComponent(CreatedContainer, CreatedContainer);
    
       	
    //now add to the project container canvas
    Application.application.MainCanvas.addChild(CreatedContainer);
}

public function Draw_Image(objLayer:Layer):void{
	
	var ProjectName:String = StripStringSpaces(Application.application._ProjectProperties._projectName.toString());
	
	var AssetFolder:String = "users/" + Application.application.currentUser + "/" + ProjectName + "/assets/";
	AssetFolder = AssetFolder.toLowerCase();
	
	//add the layer to the container area on the screen where the user can  make modifications
	var loadedImage:Image = new Image();
	loadedImage.id = objLayer.label;
	loadedImage.name = objLayer.label;
	loadedImage.source = Application.application.serverURL + AssetFolder + objLayer.obj_file_location;
	loadedImage.x = objLayer.obj_x_pos;
	loadedImage.y = objLayer.obj_y_pos;
	loadedImage.percentHeight = 100;
	loadedImage.percentWidth = 100;
	loadedImage.width = objLayer.obj_width;
	loadedImage.height = objLayer.obj_height;
	loadedImage.maintainAspectRatio = false;
	loadedImage.rotation = objLayer.obj_rotation;

	Application.application.oh.registerComponent(loadedImage, loadedImage);
	Application.application.oh.selectionManager.setSelected(loadedImage);
	
	Application.application.MainCanvas.addChild(loadedImage);
}


public function Draw_Drawing(objLayer:Layer):void{
	//create an instance of the canvas we are using
	var drawingCanvas:BlankDrawingLayerWrapper = new BlankDrawingLayerWrapper();
	drawingCanvas.id = objLayer.label;
	drawingCanvas.width=Application.application.MainCanvas.width;
	drawingCanvas.height=Application.application.MainCanvas.height;
	drawingCanvas.x=objLayer.obj_x_pos;
	drawingCanvas.y=objLayer.obj_y_pos;
	//drawingCanvas.opaqueBackground = false;
	drawingCanvas.alpha = 0;
	drawingCanvas.rotation = objLayer.obj_rotation;
		
	Application.application.MainCanvas.addChild(drawingCanvas);

}

public function LockDownMove():Boolean{
	
	var objName:String;
	var objectHandle:ObjectHandles;
				
    //get the current selected layer and clear the object handles for it
    for(var counter = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
		var CurrentLayerItem:XML = Application.application.layers.Layers.dataProvider.getItemAt(counter);				
		objName= "objHandle"+CurrentLayerItem.label;							
		objectHandle = Application.application.MainCanvas.getChildByName(objName);			
    } 
    return true;
}


public function AllowMove():Boolean{
	var objName:String;
	var objectHandle:ObjectHandles;

   // for(var counter:int = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
    	
    var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
//Alert.show("should have "+Application.application.currentLayerSelected);
    	
		//var CurrentLayerItem:XML = Application.application.layers.Layers.dataProvider.getItemAt(counter);				
		objName= "objHandle"+thisLayer.label;								
		objectHandle = Application.application.MainCanvas.getChildByName(objName);			
//		objectHandle.allowHMove = true;
//		objectHandle.allowVMove = true;

		objectHandle.addEventListener(MouseEvent.MOUSE_OUT, GrabCoordinates);
		
//Alert.show("Actually have"+objName);
	//}
    return true;
}

public function GrabCoordinates(event:MouseEvent):void{

	
	//apply the X Y coordinates to the layer information so that it can be re-drawn
	var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
	
	thisLayer.SetObjectXY(event.stageX, event.stageY);
	
	//Alert.show(Application.application._ProjectProperties.WriteXML());
	
	removeEventListener(MouseEvent.MOUSE_OUT, GrabCoordinates);
}

public function AllowResize():Boolean{
	var objName:String;
	var objectHandle:ObjectHandles;

   // for(var counter:int = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
    	
    var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
//Alert.show("should have "+Application.application.currentLayerSelected);
    		
		objName= "objHandle"+thisLayer.label;								
		objectHandle = Application.application.MainCanvas.getChildByName(objName);

		objectHandle.addEventListener(DragEvent.DRAG_COMPLETE, resizeDone);

	//}
    return true;
}

public function resizeDone(event:MouseEvent):void{

	var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
	var objName:String = "objHandle"+thisLayer.label;
	var objectHandle:ObjectHandles = Application.application.MainCanvas.getChildByName(objName);
		
		
	//get the layer type so that we can cast the object into the correct type before extracting the details we
	//need on the width and height.
	switch (thisLayer.data){
			case "Audio": 	
	//    		Draw_Audio(thisLayer.label,thisLayer.obj_x_pos, thisLayer.obj_y_pos);
		    		
	        	break;
	        case "Image":	
//	        	var ImageLayer:Image = objectHandle.getChildByName(thisLayer.label.toString()) as Image;
//Alert.show(thisLayer.label.toString());	  
//Alert.show(ImageLayer.contentHeight.toString());

//	        	thisLayer.obj_currentheight = ImageLayer.contentHeight;
//				thisLayer.obj_currentwidth = ImageLayer.contentWidth;
	        	break;
	        case "Text":
//	        	var TextLayer:TextArea = objectHandle.getChildByName(thisLayer.label.toString()) as TextArea;
//	        	thisLayer.obj_currentheight = TextLayer.height;
//	        	thisLayer.obj_currentwidth = TextLayer.width;
	        	break;
	        case "Drawing":
//	        	var DrawingLayer:BlankDrawingLayerWrapper = objectHandle.getChildByName(thisLayer.label.toString()) as BlankDrawingLayerWrapper;
//	        	thisLayer.obj_currentheight = DrawingLayer.height;
//	        	thisLayer.obj_currentwidth = DrawingLayer.width;
	        	break;
		        
			default:
	        	
	        	break;
	 }
		 

//Alert.show(Application.application._ProjectProperties.WriteXML());	
	//removeEventListener(DragEvent.DRAG_COMPLETE, resizeDone);
	
}

public function AllowRotate():void{
	var objName:String;
	var objectHandle:ObjectHandles;

   // for(var counter:int = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
    	
    var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
//Alert.show("should have "+Application.application.currentLayerSelected);
    	
		//var CurrentLayerItem:XML = Application.application.layers.Layers.dataProvider.getItemAt(counter);				
		objName= "objHandle"+thisLayer.label;								
		objectHandle = Application.application.MainCanvas.getChildByName(objName);
//		objectHandle.allowRotate = true;
//		objectHandle.alwaysMaintainAspectRatio = false;
		
}



public function LockDown():void{
		
	var objName:String;
	var objectHandle:ObjectHandles;
				
    //get the current selected layer and clear the object handles for it
    for(var counter = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
		var CurrentLayerItem:XML = Application.application.layers.Layers.dataProvider.getItemAt(counter);				
		objName= "objHandle"+CurrentLayerItem.label;							
		objectHandle = Application.application.MainCanvas.getChildByName(objName);			
		
		//stop rotate
//		objectHandle.allowRotate = false;
		
		//stop move
//		objectHandle.allowHMove = false;
//		objectHandle.allowVMove = false;
		
		//stop scale
//		objectHandle.alwaysMaintainAspectRatio = false;
		
		
    } 
}

public function AllowScale():void{
	var objName:String;
	var objectHandle:ObjectHandles;

   // for(var counter:int = 0; counter<Application.application.layers.Layers.dataProvider.length; counter++){
    	
    var thisPage:Page = new Page();
	thisPage = Application.application._ProjectProperties._pages[Application.application.currentPageSelected];
	var thisLayer:Layer = new Layer();
	thisLayer = thisPage.layers[Application.application.currentLayerSelected];
//Alert.show("should have "+Application.application.currentLayerSelected);
		
		objName= "objHandle"+thisLayer.label;								
		objectHandle = Application.application.MainCanvas.getChildByName(objName);

		
		objectHandle.addEventListener(MouseEvent.MOUSE_OUT, resizeDone);
		
}

/******************************************
 * Function to draw the components that will
 * always be displayed on screen inc uni logo
 * page numbers, home, forward navigation 
 * ****************************************/
private function drawCompulsoryComponents():Boolean{
	
	var separationValue:int = new int();
	var constGap:int = new int();
	
	constGap = 5;
	
	//add the logo at the top right of the screen and lock for editing
	var UniLogo:Image = new Image();
	UniLogo.id = "University Logo";
	UniLogo.name = "University Logo";
	UniLogo.source = Application.application.serverURL + "images/lulogo.gif";
	UniLogo.x = 570;
	UniLogo.y = 15;
		
	Application.application.MainCanvas.addChild(UniLogo);
	
	//add the next button if required
	if (Application.application._ProjectProperties._displayNextButton == true){
		var NextBtn:Image = new Image();
		NextBtn.id = "Next Button";
		NextBtn.name = "Next Button";
		NextBtn.source = Application.application.serverURL +"images/output_fixtures/next.jpg";
		NextBtn.x = 10;
		NextBtn.y = 550;
		
		separationValue = constGap + NextBtn.x + 97;
		
		Application.application.MainCanvas.addChild(NextBtn);
	}	
	
	//add the previous button
	if (Application.application._ProjectProperties._displayPreviousButton==true){
		var PreviousBtn:Image = new Image();
		PreviousBtn.id = "Next Button";
		PreviousBtn.name = "Next Button";
		PreviousBtn.source = Application.application.serverURL +"images/output_fixtures/previous.jpg";
		PreviousBtn.x = separationValue;
		PreviousBtn.y = 550;
		
		Application.application.MainCanvas.addChild(PreviousBtn);
		
		separationValue = constGap + PreviousBtn.x + 97;
	}
	
	//add the home button
	if (Application.application._ProjectProperties._displayHomeButton == true){
		var HomeBtn:Image = new Image();
		HomeBtn.id = "Home Button";
		HomeBtn.name = "Home Button";
		HomeBtn.source = Application.application.serverURL + "images/output_fixtures/home.jpg";
		HomeBtn.x = separationValue;
		HomeBtn.y = 550;
		
		Application.application.MainCanvas.addChild(HomeBtn);
		
		separationValue = constGap + HomeBtn.x + 49;
	}
	
	//add the page number buttons
	
	separationValue = separationValue + 30;
	
	if (Application.application._ProjectProperties._displayNumbers == true){
		//for the moment just have a number of numbers across the bottom at the moment 5 - 8 
		for (var i:int = 1; i<6; i++){
			var NumberButton:Image = new Image();
			NumberButton.id = "NumberBtn" + i.toString();
			NumberButton.name = "NumberBtn" + i.toString();
			var ImageFileName:String = new String();
			ImageFileName = i.toString() + ".jpg";
			NumberButton.source = Application.application.serverURL + "images/output_fixtures/" + ImageFileName;
			NumberButton.x = separationValue;
			NumberButton.y = 550;
			
			Application.application.MainCanvas.addChild(NumberButton);
			
			separationValue = separationValue + 45;
			
		}
	}
	
	//add the copyright statement
	if (Application.application._ProjectProperties._displayCopyright.length>=0){
		var CopyrightStatement:Label = new Label();
		CopyrightStatement.id = "Copyright";
		CopyrightStatement.name = "Copyright";
		CopyrightStatement.text = "Copyright " + Application.application._ProjectProperties._displayCopyright;
		CopyrightStatement.x = 570;
		CopyrightStatement.y = 575;
		
		Application.application.MainCanvas.addChild(CopyrightStatement);
	}
	
	return true;
}
